package com.example.demo_redis_test.redis.RedEnvelope;

import org.springframework.data.redis.core.StringRedisTemplate;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

public class RedEnvelope {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    private static final int SLEEPTIME = 50;
    /**
     * 获取分布式锁  2019
     * @param lockKey
     * @param timeout
     * @param unit
     */
    public boolean getLock(String lockKey, String value, long timeout, TimeUnit unit){
        boolean lock = false;
        while (!lock) {
            //设置key自己的超时时间
            lock = stringRedisTemplate.opsForValue().setIfAbsent(lockKey, value,timeout,unit);
            if (lock) { //已经获取了这个锁 直接返回已经获得锁的标识
                return lock;
            }
            try {
                //暂停50ms,重新循环
                Thread.sleep(SLEEPTIME);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        return lock;
    }

    /**
     * 获取指定key的值
     * @param key
     */
    public String getKey(String key){
        return stringRedisTemplate.opsForValue().get(key);
    }
    /**
     * 设置指定 key的值
     */
    public void set(String key,String value){
        stringRedisTemplate.opsForValue().set(key,value);
    }
}
